<template>
    <div style="width: 360px;margin: auto;">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="userInfo" :rules="rules" label-width="auto"
            status-icon>
            <el-form-item label="用户名：" prop="loginName">
                <el-input v-model="userInfo.loginName" />
            </el-form-item>
            <el-form-item label="密码：" prop="passWord">
                <el-input v-model="userInfo.passWord" show-password />
            </el-form-item>
            <el-form-item label="确认密码：" prop="newPassWord">
                <el-input v-model="userInfo.newPassWord" show-password />
            </el-form-item>
            <el-form-item label="所在部门" prop="departmentId">
                <el-select v-model="userInfo.departmentId" placeholder="请选择部门" style="width: 100%;">
                    <el-option v-for="item in departmentInfo" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="性别：" prop="userGender">
                <el-radio-group v-model="userInfo.userGender">
                    <el-radio :value="true">男</el-radio>
                    <el-radio :value="false">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="所在地址：" prop="address">
                <!-- 使用树形列表显示 （后台显示） -->
                <!-- <el-tree style="max-width: 600px" :data="countyInfoList" :props="defaultProps" /> -->
                <!-- <el-tree-select v-model="userInfo.address" :data="countyInfoList" :props="defaultProps":render-after-expand="false" /> -->
                <!-- <el-cascader v-model="userInfo.address" :options="countyInfoList" :props="defaultProps" clearable
                    style="width: 100%;" /> -->
                <!-- 前台获取省市县数据(使用clearable时，清空数据值将改变) -->
                <el-cascader size="large" :options="options" v-model="userInfo.address" @change="handleChange"
                    style="width: 100%;" />
            </el-form-item>
            <el-form-item label="详细地址：" prop="fullAddress">
                <el-input type="textarea" row="3" v-model="userInfo.fullAddress" />
            </el-form-item>
            <el-form-item>
                <el-button style="margin: auto;" type="primary" @click="insertUserInfo(ruleFormRef)">添加</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { regionData, codeToText } from 'element-china-area-data'

// 定义变量
import http from '@/http'
const router = useRouter()

// 定义变量
// const countyInfoList = ref([])

// 默认属性设置
// const defaultProps = {
//     children: 'children',
//     label: 'name',
//     value: 'name',
//     pinyin: 'pinyin',
//     firstPinyin: 'firstPinyin'
// }

// 获取省市县树形结构列表
// const getCountyInfoList = () => {
//     http.get("/api/User/GetTree").then(res => {
//         countyInfoList.value = res.data;
//     })
// }

// 用户信息
const userInfo = reactive({
    loginName: "",
    userGender: true,
    passWord: "",
    newPassWord: "",
    userProvince: "",
    userCity: "",
    userArea: "",
    address: [],
    fullAddress: "",
    createPerson: "string",
    createDate: "2024-03-21T14:27:55.439Z",
    revisePerson: "string",
    reviseDate: "2024-03-21T14:27:55.439Z",
    isDelete: false,
    departmentId: ""
})

const departmentInfo = [
    {
        value: 1,
        label: 'IT资源部',
    },
    {
        value: 2,
        label: '人力资源部',
    },
    {
        value: 3,
        label: '财务部',
    },
    {
        value: 4,
        label: '销售部',
    },
    {
        value: 5,
        label: '行政部',
    },
]

// 用户地址
// const address = ref([] as Array<string>)

// 校验规则
const ruleFormRef = ref<FormInstance>()
const rules = reactive({
    loginName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    passWord: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ],
    newPassWord: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
    ],
    address: [
        {
            required: true,
            message: '请选择用户地址',
            trigger: 'change',
        },
    ],
    departmentId: [
        {
            required: true,
            message: '请选择所在部门',
            trigger: 'change',
        },
    ],
    fullAddress: [
        { required: true, message: '请填写详细地址', trigger: 'blur' },
    ],
})

// 用户添加
const insertUserInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            if (userInfo.passWord != userInfo.newPassWord) {
                ElMessage({
                    type: 'error',
                    message: '密码不一致，请重新输入！',
                    duration: 1000
                });
                return;
            }
            // 用户所在省
            userInfo.userProvince = userInfo.address[0];
            // 用户所在市
            userInfo.userCity = userInfo.address[1];
            // 用户所在县
            userInfo.userArea = userInfo.address[2];
            console.log(userInfo);
            // 用户添加功能
            http.post("/api/User/UserInsert", userInfo).then(res => {
                // 用户添加成功
                if (res.data > 0) {
                    ElMessage({
                        type: 'success',
                        message: '添加成功',
                        duration: 1000
                    });
                    // 跳转用户列表
                    router.push('/userListView')
                }
                // 用户名重复
                else if (res.data == -1) {
                    ElMessage({
                        type: 'error',
                        message: '用户名重复，请重新输入',
                        duration: 1000
                    })
                }
                // 添加失败
                else {
                    ElMessage({
                        type: 'error',
                        message: '添加失败',
                        duration: 1000
                    })
                }
            })
        }
    })
}


// 省市县三级联动（前台）

const options = ref(regionData)

const handleChange = () => {
    if (
        userInfo.address[0] != null &&
        userInfo.address[1] != null &&
        userInfo.address[2] != null
    ) {
        const str =
            codeToText[userInfo.address[0]] +
            '/' +
            codeToText[userInfo.address[1]] +
            '/' +
            codeToText[userInfo.address[2]]
    }
}

// onMounted(() => {
//     getCountyInfoList();
// })
</script>

<style scoped></style>